package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.SearchSimpleActivity;
import com.jp.knowledge.activity.TeamCircleCreateActivity;
import com.jp.knowledge.adapter.team_circle.TeamCircleViewPagerAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InteractDataModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.OrganizeActivity;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.service.LatestStateService;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.TabView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 528787067@qq.com on 2017/3/15.
 */
public class TeamCircleFragment extends BaseFragment implements View.OnClickListener, ResultSubscriber.OnResultListener {

    private static final int PUSH_DYNAMIC_CODE = 0x01;
    private static final int PUSH_BROKE_CODE = 0x02;
    private static final int GET_COMPANY_LIST_CODE = 0x03;

    private static int pageIndex;
    private static Map<String, Integer> scrollYMap = new HashMap<>();

    private View contentView;
    private Context context;

    private ImageView searchBn;
    private ImageView createBn;
    private LinearLayout teamCirleContentView;
    private TabView tabView;
    private ViewPager teamCircleViewPager;

    private LinearLayout teamCircleRemindView;
    private TextView teamCircleRemindName;
    private TextView teamCircleRemindDetail;
    private TextView teamCircleRemindBtn;

    private LinearLayout joinView;
    private TextView joinBtn;

    private List<String> tabNames;
    private List<OrganizaModel> organizaModels;
    private List<Fragment> fragments;
    private TeamCircleViewPagerAdapter pagerAdapter;

    private PopupWindow createPopupWindow;
    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    private FileCacheManager cacheManager;
    private String cachePath;

    private String openFragmentCompanyId;

    public void setOpenFragmentCompanyId(String openFragmentCompanyId) {
        this.openFragmentCompanyId = openFragmentCompanyId;
        if(teamCircleViewPager != null && openFragmentCompanyId != null){
            for(int i = 0; i < organizaModels.size(); i++) {
                if(openFragmentCompanyId.equals(organizaModels.get(i).getCompanyId())){
                    teamCircleViewPager.setCurrentItem(i);
                    pageIndex = i;
                    break;
                }
            }
            this.openFragmentCompanyId = null;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null){
            this.context = getContext();
            tabNames = new ArrayList<>();
            organizaModels = new ArrayList<>();
            fragments = new ArrayList<>();
            initView();
            init();
            getCompanyList();
            teamCircleViewPager.setCurrentItem(pageIndex);
            for(int i = 0; i < fragments.size(); i++){
                TeamCircleDataShowFragment fragment = (TeamCircleDataShowFragment) fragments.get(i);
                if(scrollYMap.get(fragment.getCompanyId()) != null)
                    fragment.setScrollY(scrollYMap.get(fragment.getCompanyId()));
            }
        }
        return contentView;
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        pageIndex = teamCircleViewPager.getCurrentItem();
        scrollYMap.clear();
        for(int i = 0; i < fragments.size(); i++){
            TeamCircleDataShowFragment fragment = (TeamCircleDataShowFragment) fragments.get(i);
            scrollYMap.put(fragment.getCompanyId(), fragment.getScrollY());
        }
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != RESULT_OK || data == null)
            return;
        if((requestCode == PUSH_DYNAMIC_CODE || requestCode == PUSH_BROKE_CODE)
                && getCallBack() != null){
//            getCallBack().refreshData();
            String companyId = data.getStringExtra("companyId");
            int companyType = data.getIntExtra("companyType", -1);
            if(companyId == null || companyId.trim().length() == 0 || companyType == -1)
                return;
            for(Fragment fragment : fragments){
                TeamCircleDataShowFragment teamCircleDataShowFragment = (TeamCircleDataShowFragment) fragment;
                if(companyId.equals(teamCircleDataShowFragment.getCompanyId())){
                    teamCircleDataShowFragment.refreshData();
                    break;
                }
            }
        }
    }

    private void initView(){
        contentView = LayoutInflater.from(context).inflate(R.layout.fragment_main_team_circle, null);

        createBn = (ImageView) contentView.findViewById(R.id.icon_right);
        searchBn = (ImageView) contentView.findViewById(R.id.icon_serach);

        teamCircleRemindView = (LinearLayout) contentView.findViewById(R.id.team_circle_remind_view);
        teamCircleRemindName = (TextView) contentView.findViewById(R.id.team_circle_remind_name);
        teamCircleRemindDetail = (TextView) contentView.findViewById(R.id.team_circle_remind_detail);
        teamCircleRemindBtn = (TextView) contentView.findViewById(R.id.team_circle_remind_btn);

        teamCirleContentView = (LinearLayout) contentView.findViewById(R.id.team_circle_data_view);
        tabView = (TabView) contentView.findViewById(R.id.tab_view);
        teamCircleViewPager = (ViewPager) contentView.findViewById(R.id.team_circle_viewpager);

        joinView = (LinearLayout) contentView.findViewById(R.id.team_circle_join_lly);
        joinBtn = (TextView) contentView.findViewById(R.id.team_circle_join_btn);
        joinBtn.setOnClickListener(this);

//        teamCircleTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        teamCircleRemindBtn.setOnClickListener(this);

        pagerAdapter = new TeamCircleViewPagerAdapter(getActivity().getSupportFragmentManager(), fragments);
        teamCircleViewPager.setAdapter(pagerAdapter);
        tabView.setTabItems(tabNames);
        tabView.setupWithViewPager(teamCircleViewPager);
    }

    private void init(){
        initBroadCast();
        initCache();
        initTitleBar();
        initPopupWindow();
//        setTeamCircleShowView();
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(context);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.GET_LOGIN_INFO.equals(action)) {
                    getCompanyList();
                } else if(LocalBroadCast.LOGOUT_SUCCESS_BROD.equals(action)) {
                    organizaModels.clear();
                    setTeamCircleShowView();
                } else if(LocalBroadCast.COMPANY_JOIN.equals(action)){
//                    OrganizaModel organizaModel = (OrganizaModel) intent.getSerializableExtra("joinCompany");
//                    int index = intent.getIntExtra("index", 0);
//                    if(organizaModel == null)
//                        return;
//                    if(!organizaModels.contains(organizaModel))
//                        organizaModels.add(index, organizaModel);
                    organizaModels = application.getUserData().getCompanyList();
                    setTeamCircleContentView();
                } else if(LocalBroadCast.COMPANY_EXIT.equals(action)){
                    String companyId =  intent.getStringExtra("companyId");
                    if(companyId == null)
                        return;
                    for(OrganizaModel organizaModel : organizaModels)
                        if(companyId.equals(organizaModel.getCompanyId())) {
                            organizaModels.remove(organizaModel);
                            break;
                        }
                    setTeamCircleContentView();
                } else if(LocalBroadCast.COMPANY_SORT.equals(action)){
                    List<String> companyIds = intent.getStringArrayListExtra("companyIds");
                    List<OrganizaModel> companyModels = new ArrayList<>();
                    for(String companyId : companyIds){
                        for(OrganizaModel organizaModel : organizaModels){
                            if(organizaModel.getCompanyId().equals(companyId)){
                                companyModels.add(organizaModel);
                                break;
                            }
                        }
                    }
                    organizaModels.clear();
                    organizaModels.addAll(companyModels);
                    setTeamCircleContentView();
                } else if(LocalBroadCast.GET_INTERACT_DATA_CODE.equals(action)){
                    setTabColor();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
        intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        intentFilter.addAction(LocalBroadCast.COMPANY_JOIN);
        intentFilter.addAction(LocalBroadCast.COMPANY_EXIT);
        intentFilter.addAction(LocalBroadCast.COMPANY_SORT);
        intentFilter.addAction(LocalBroadCast.GET_INTERACT_DATA_CODE);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    private void initCache(){
        cacheManager = new FileCacheManager();
        cachePath = getContext().getCacheDir().getPath() + "/team_circle_company";
        if (application.getUserData() != null)
            cachePath += ("_" + application.getUserData().getUuid());
        cachePath += ".dat";
    }

    private void initTitleBar(){
        ((TextView)contentView.findViewById(R.id.module_name)).setText(R.string.team_circle_title);
        ((TextView)contentView.findViewById(R.id.module_desc)).setText(R.string.team_circle_title_desc);

        createBn.setImageResource(R.mipmap.edit);
        createBn.setVisibility(View.VISIBLE);

        searchBn.setOnClickListener(this);          // 搜索
        createBn.setOnClickListener(this);          // 新建编辑
        searchBn.setVisibility(View.GONE);

        leftIcon = (ImageView) contentView.findViewById(R.id.icon_left);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setVisibility(View.VISIBLE);
        leftIcon.setOnClickListener(this);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            int statusBarHeight = 0;
//            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
//            if (resourceId > 0)
//                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
//            contentView.findViewById(R.id.top_bar).setPadding(0, statusBarHeight, 0, 0);
//        }
//        contentView.findViewById(R.id.top_bar).setVisibility(View.GONE);
    }

    public void setTitleBarVisibility(boolean isVisibility){
        contentView.findViewById(R.id.top_bar).setVisibility(isVisibility ? View.VISIBLE : View.GONE);
    }

    private void initPopupWindow(){
        View view = View.inflate(context, R.layout.team_circle_create_popupwindow, null);
        view.findViewById(R.id.team_circle_create_dynamic).setOnClickListener(this);
        view.findViewById(R.id.team_circle_create_broke).setOnClickListener(this);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        createPopupWindow = new PopupWindow(view, view.getMeasuredWidth(), view.getMeasuredHeight(), true);
        createPopupWindow.setOutsideTouchable(true);
        createPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
    }

    private void setTeamCircleShowView(){
//        UserData userData = getUserData();
//        if(userData == null || userData.getIsLogin() != 1){     // 没登录
//            createBn.setVisibility(View.GONE);
//            teamCirleContentView.setVisibility(View.GONE);
//            teamCircleRemindView.setVisibility(View.VISIBLE);
//            teamCircleRemindName.setVisibility(View.GONE);
//            teamCircleRemindDetail.setText("登录后才能使用团队圈");
//            teamCircleRemindBtn.setText("登录");
//            teamCircleRemindBtn.setTag(0);
//        } else if(userData.getCompanyId() == null && userData.getCompanyId().trim().length() == 0){ // 登陆未加公司
//            createBn.setVisibility(View.GONE);
//            teamCirleContentView.setVisibility(View.GONE);
//            teamCircleRemindView.setVisibility(View.VISIBLE);
//            teamCircleRemindName.setVisibility(View.GONE);
//            teamCircleRemindDetail.setText("加入你所在的组织才能使用团队圈");
//            teamCircleRemindBtn.setText("加入组织");
//            teamCircleRemindBtn.setTag(1);
//        } else{     // 已登录、加入公司、公司通过认证
//            createBn.setVisibility(View.VISIBLE);
//            teamCircleRemindView.setVisibility(View.GONE);
//            teamCirleContentView.setVisibility(View.VISIBLE);
//            setTeamCircleContentView();
//        }
        createBn.setVisibility(View.VISIBLE);
        teamCircleRemindView.setVisibility(View.GONE);
        teamCirleContentView.setVisibility(View.VISIBLE);
        setTeamCircleContentView();
    }

    private void setTeamCircleContentView(){
        UserData userData = getUserData();

        // 剔除掉没有通过审核的公司
        List<OrganizaModel> unShowCompany = new ArrayList<>();
        for(OrganizaModel organizaModel : organizaModels){
            if(organizaModel.getCompanyState() == 1
                    && (organizaModel.getAuditStete() == 0 || organizaModel.getAuditStete() == 2))
                unShowCompany.add(organizaModel);
        }
        for(OrganizaModel organizaModel : unShowCompany)
            organizaModels.remove(organizaModel);

        if(userData == null || organizaModels.size() == 0) {
            organizaModels.add(new OrganizaModel());
            tabView.setVisibility(View.GONE);
            joinView.setVisibility(View.VISIBLE);
        } else {
            if(organizaModels.size() > 1){
                List<OrganizaModel> tempOrganizaModels = new ArrayList<>();
                for(OrganizaModel organizaModel : organizaModels)
                    if(organizaModel.getCompanyId() == null)
                        tempOrganizaModels.add(organizaModel);
                for(OrganizaModel organizaModel : tempOrganizaModels)
                    organizaModels.remove(organizaModel);
            }
            joinView.setVisibility(View.GONE);
            if (organizaModels.size() > 1)
                tabView.setVisibility(View.VISIBLE);
            else
                tabView.setVisibility(View.GONE);
        }
        List<Fragment> tempFragment = new ArrayList<>();
        for(OrganizaModel organizaModel : organizaModels){
            boolean isExist = false;
            for (Fragment fragment : fragments){
                TeamCircleDataShowFragment teamCircleDataShowFragment = (TeamCircleDataShowFragment) fragment;
                // 判断 fragment 是否存在，如果存在则直接加入，否则创建新的 fragment
                if ((organizaModel.getCompanyId() == null && teamCircleDataShowFragment.getCompanyId() == null)
                    || (organizaModel.getCompanyId() != null && organizaModel.getCompanyId().equals(teamCircleDataShowFragment.getCompanyId()))) {
                    tempFragment.add(fragment);
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                TeamCircleDataShowFragment teamCircleDataShowFragment = new TeamCircleDataShowFragment().newInstance(organizaModel.getCompanyId(),
                        organizaModel.getCompanyType(),
                        organizaModel.getCompanyName(),
                        organizaModel.getAuditStete(),
                        1,
                        organizaModel.getScoopCover());
                tempFragment.add(teamCircleDataShowFragment);
            }
        }
        fragments.clear();
        fragments.addAll(tempFragment);
        pagerAdapter.notifyDataSetChanged();
        tabView.setOnTabItemClickListener(new TabView.TabItemClickListener() {
            @Override
            public void onTabClick(int preIndex, int selecIndex) {}
            @Override
            public void onTabReclick(int selectIndex) {
                if(getCallBack() != null)
                    getCallBack().refreshData();
            }
        });
        tabNames.clear();
        for(int i = 0; i < organizaModels.size(); i++) {
            String tabName = organizaModels.get(i).getCompanyName();
            if(tabName == null)
                tabName = "";
            tabNames.add(tabName);
        }
        tabView.setTabItems(tabNames);
        setTabColor();
        setOpenFragmentCompanyId(openFragmentCompanyId);
    }

    private void setTabColor(){
        InteractDataModel interactDataModel = LatestStateService.getInteractDataModel();
        if(interactDataModel == null || interactDataModel.getList() == null || interactDataModel.getList().size() == 0){
            for(int i = 0; i < tabView.getTabCount(); i++)
                ((TabView.TabItem)tabView.getTabAt(i)).setUnselectTextColor(ContextCompat.getColor(context, R.color.tab_view_unselect_text_color));
            return;
        }
        for(int i = 0; i < fragments.size(); i++){
            TeamCircleDataShowFragment fragment = (TeamCircleDataShowFragment) fragments.get(i);
            TabView.TabItem tabItem = (TabView.TabItem)tabView.getTabAt(i);
            for(InteractDataModel.ListBean listBean : interactDataModel.getList()){
                if(fragment.getCompanyId() != null
                        && fragment.getCompanyId().equals(listBean.getCompanyId())
                        && listBean.getCount() > 0){
                    tabItem.setSelectTextColor(ContextCompat.getColor(context, R.color.google_red));
                    tabItem.setUnselectTextColor(ContextCompat.getColor(context, R.color.google_red));
                    break;
                } else{
                    tabItem.setSelectTextColor(ContextCompat.getColor(context, R.color.tab_view_select_text_color));
                    tabItem.setUnselectTextColor(ContextCompat.getColor(context, R.color.tab_view_unselect_text_color));
                }
            }
        }
    }

    private void getCompanyList(){
//        JsonObject param = new JsonObject();
//        param.addProperty("token", HttpHelper.token);
//        HttpHelper.getInstance(context).getAllOrganiza(param, GET_COMPANY_LIST_CODE, this);
        UserData userData = application.getUserData();
        organizaModels.clear();
        if(userData != null && userData.getCompanyList() != null) {
            List<OrganizaModel> companyList = userData.getCompanyList();
            if (companyList != null && companyList.size() > 0)
                organizaModels.addAll(companyList);
        }
        setTeamCircleShowView();
    }

    private UserData getUserData(){
        return ((JpApplication)getActivity().getApplication()).getUserData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                getActivity().onBackPressed();
                break;
            case R.id.icon_right:           // 创建
//                createPopupWindow.showAsDropDown(createBn,
//                        -createPopupWindow.getWidth()+createBn.getWidth()/2, 0);
//                createPopupWindow.dismiss();

                Intent createIntent = new Intent(context, TeamCircleCreateActivity.class);
                createIntent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 1);
                createIntent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 1);
                try {
                    OrganizaModel currentCompany = organizaModels.get(teamCircleViewPager.getCurrentItem());
                    createIntent.putExtra(TeamCircleCreateActivity.COMPANY_ID, currentCompany.getCompanyId());
                    createIntent.putExtra(TeamCircleCreateActivity.COMPANY_TYPE, currentCompany.getCompanyType());
                    createIntent.putExtra(TeamCircleCreateActivity.COMPANY_NAME, currentCompany.getCompanyName());
                } catch (Exception e){} finally {
                    startActivityForResult(createIntent, PUSH_DYNAMIC_CODE);
                }
                break;
            case R.id.icon_serach:          // 搜索
                SearchSimpleActivity.gotoSearch(context, 16, -1, null, false);
                break;
            case R.id.team_circle_create_dynamic: // 发表动态
                Intent dynamicIntent = new Intent(context, TeamCircleCreateActivity.class);
                dynamicIntent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 1);
                dynamicIntent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 0);
                startActivityForResult(dynamicIntent, PUSH_DYNAMIC_CODE);
                createPopupWindow.dismiss();
                break;
            case R.id.team_circle_create_broke:   // 我要爆料
                Intent brokeIntent = new Intent(context, TeamCircleCreateActivity.class);
                brokeIntent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 1);
                brokeIntent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 3);
                startActivityForResult(brokeIntent, PUSH_BROKE_CODE);
                createPopupWindow.dismiss();
                break;
            case R.id.team_circle_remind_btn:
                int btnType = (int) v.getTag();
                if(btnType == 1)           // 加入组织
                    startActivity(new Intent(context, OrganizeActivity.class));
                else if(btnType == 2)    // 更换组织
                    startActivity(new Intent(context, OrganizeActivity.class));
                else                     // 登陆
                    startActivity(new Intent(context, LoginActivity.class));
                break;
            case R.id.team_circle_join_btn: // 未加入是加入按钮
                if(!application.isLogin())
                    startActivity(new Intent(context, LoginActivity.class));
                else
                    startActivity(new Intent(context, OrganizeActivity.class));
                break;
        }
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {}
    @Override
    public void onNext(IModel data, int requestType) {
        organizaModels.clear();
        List<OrganizaModel> companyList = data.getList(OrganizaModel.class);
        if(companyList != null && companyList.size() > 0)
            organizaModels.addAll(companyList);
        if(application.getUserData() != null)
            application.getUserData().setCompanyList(organizaModels);
        setTeamCircleShowView();
    }

    private FragmentCallBack getCallBack(){
        if(fragments == null || fragments.size() == 0
                || teamCircleViewPager == null || teamCircleViewPager.getAdapter().getCount() == 0)
            return null;
        return (FragmentCallBack)fragments.get(teamCircleViewPager.getCurrentItem());
    }

    /* 用于回调 Fragment */
    public interface FragmentCallBack {
        void refreshData();
    }
}
